//
//  EquipmentListViewController.m
//  
//
//  Created by qkong on 15/6/15.
//
//

#import "EquipmentListViewController.h"
#import "QAirAppDelegate.h"
#import "EquipmentTableViewCell.h"
#import "Tool.h"
#import <CoreBluetooth/CoreBluetooth.h>
@interface EquipmentListViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *equipListTable;

@property (strong, nonatomic) NSMutableArray *equipments;

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *scanIndicator;

@property (weak, nonatomic) IBOutlet UIButton *scanBtn;

@property (nonatomic)  BOOL isScanning;

@end

@implementation EquipmentListViewController

- (void)setIsScanning:(BOOL)isScanning{
    _isScanning = isScanning;
    [self.scanBtn setTitle:isScanning?@"停止":@"扫描" forState:UIControlStateNormal];
    QAirAppDelegate *delegate = (QAirAppDelegate *)[UIApplication sharedApplication].delegate;
    if (isScanning) {
        [delegate startScan];
        [self.scanIndicator startAnimating];
    }else{
        [delegate stopScan];
        [self.scanIndicator stopAnimating];
    }
}

- (NSMutableArray *)equipments{
    if (!_equipments) {
        _equipments = [[NSMutableArray alloc]init];
    }
    return _equipments;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initListTable];
    self.scanIndicator.hidesWhenStopped = YES;
    // Do any additional setup after loading the view from its nib.
}

- (void)initListTable{
    self.equipListTable.delegate = self;
    self.equipListTable.dataSource = self;
    self.equipListTable.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    if ([self.equipListTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.equipListTable setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.equipListTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.equipListTable setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.isScanning = YES;
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(updatePeripherals:)
                                                name:PERIPHERALS_UPDATE_NOTIFICATIOTN_NAME
                                              object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(didReceiveReturnData)
                                                name:UPDATE_QAIR_NOTIFICATION_NAME
                                              object:nil];
    QAirAppDelegate *delegate = (QAirAppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate startScan];
}


- (void)updatePeripherals:(NSNotification *)notification{
    self.equipments = notification.userInfo[kKeyNotificationUserInfoPeripherals];
    [self.equipListTable reloadData];
}

- (void)didReceiveReturnData{
    QAirAppDelegate *delegate = (QAirAppDelegate *)[UIApplication sharedApplication].delegate;
    [self dismissViewControllerAnimated:YES completion:^{
        [delegate.container setMenuState:MFSideMenuStateClosed];
    }];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:PERIPHERALS_UPDATE_NOTIFICATIOTN_NAME
                                                 object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:UPDATE_QAIR_NOTIFICATION_NAME
                                                 object:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.equipments.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    QAirAppDelegate *delegate = (QAirAppDelegate *)[UIApplication sharedApplication].delegate;
    CBPeripheral *peripheral = delegate.peripherals[indexPath.row][kKeyNotificationUserInfoPeripherals];
    [delegate connectToPeripheral:peripheral];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"EquipmentCell";
    EquipmentTableViewCell *cell = (EquipmentTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"EquipmentTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    NSDictionary *indexPeripheral = [self.equipments objectAtIndex:indexPath.row];
    CBPeripheral *peripheral = indexPeripheral[kKeyNotificationUserInfoPeripherals];
    NSNumber *RSSI = indexPeripheral[kKeyNotificationUserInfoRSSI];
    [cell setPeripheralWithName:peripheral.name mac:@"2" RSSI:[NSString stringWithFormat:@"%@",RSSI]];
    return cell;
}

- (IBAction)backAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (IBAction)scanPerpherals:(id)sender {
    self.isScanning = !self.isScanning;
}

@end
